package com.skyolder.milkbee.web.rest;

import com.codahale.metrics.annotation.Timed;
import com.skyolder.milkbee.domain.Card;
import com.skyolder.milkbee.domain.Leaguer;
import com.skyolder.milkbee.domain.Moderator;
import com.skyolder.milkbee.security.AuthoritiesConstants;
import com.skyolder.milkbee.security.SecurityUtils;
import com.skyolder.milkbee.service.CardService;
import com.skyolder.milkbee.service.LeaguerService;
import com.skyolder.milkbee.service.ModeratorService;
import com.skyolder.milkbee.web.rest.util.HeaderUtil;
import com.skyolder.milkbee.web.rest.util.PaginationUtil;

import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Optional;

/**
 * REST controller for managing Moderator.
 */
@RestController
@RequestMapping("/api")
public class ModeratorResource {

    private final Logger log = LoggerFactory.getLogger(ModeratorResource.class);
        
    @Inject
    private ModeratorService moderatorService;
    @Inject
	private LeaguerService leaguerService;
    @Inject
    private CardService cardService;

    /**
     * POST  /moderators : Create a new moderator.
     *
     * @param moderator the moderator to create
     * @return the ResponseEntity with status 201 (Created) and with body the new moderator, or with status 400 (Bad Request) if the moderator has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/moderators")
    @Timed
    public ResponseEntity<Moderator> createModerator(@RequestBody Moderator moderator) throws URISyntaxException {
        log.debug("REST request to save Moderator : {}", moderator);
        if (moderator.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("moderator", "idexists", "A new moderator cannot already have an ID")).body(null);
        }
        if(!SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.ADMIN)){
    		return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("moderator", "no Authorities", "you do not have Authorities")).body(null);
    	}
        Leaguer leaguer=leaguerService.findOne(moderator.getLeaguerId());
        if(leaguer==null){
        	 return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("moderator", "no user", "bad leaguer id")).body(null);
        }
        Moderator oldModerator=moderatorService.findOneByLeaguerIdAndCategoryId(moderator.getLeaguerId(),moderator.getCategoryId());
        if(oldModerator!=null){
       	 return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("moderator", "user exist", "the user has been moderator")).body(null);
        }
        moderator.setUserId(leaguer.getUserId());
        moderator.setCreatedAt(ZonedDateTime.now());
        Moderator result = moderatorService.save(moderator);
        return ResponseEntity.created(new URI("/api/moderators/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert("moderator", result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /moderators : Updates an existing moderator.
     *
     * @param moderator the moderator to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated moderator,
     * or with status 400 (Bad Request) if the moderator is not valid,
     * or with status 500 (Internal Server Error) if the moderator couldnt be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/moderators")
    @Timed
    public ResponseEntity<Moderator> updateModerator(@RequestBody Moderator moderator) throws URISyntaxException {
        log.debug("REST request to update Moderator : {}", moderator);
        if (moderator.getId() == null) {
            return createModerator(moderator);
        }
        Moderator result = moderatorService.save(moderator);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert("moderator", moderator.getId().toString()))
            .body(result);
    }

    /**
     * GET  /moderators : get all the moderators.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of moderators in body
     * @throws URISyntaxException if there is an error to generate the pagination HTTP headers
     */
    @GetMapping("/moderators")
    @Timed
    public ResponseEntity<List<Moderator>> getAllModerators(@ApiParam Pageable pageable)
        throws URISyntaxException {
        log.debug("REST request to get a page of Moderators");
        Page<Moderator> page = moderatorService.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/moderators");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }
    @GetMapping("/allmoderator/{cardId}")
    @Timed
    public ResponseEntity<List<Moderator>> getAllModeratorsByCard(@PathVariable Long cardId)
    		throws URISyntaxException {
    	Card card=cardService.findOne(cardId);
    	List<Moderator> list = moderatorService.doQueryAllByCategoryId(card.getId());
    	return new ResponseEntity<>(list, HttpStatus.OK);
    }

    /**
     * GET  /moderators/:id : get the "id" moderator.
     *
     * @param id the id of the moderator to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the moderator, or with status 404 (Not Found)
     */
    @GetMapping("/moderators/{id}")
    @Timed
    public ResponseEntity<Moderator> getModerator(@PathVariable Long id) {
        log.debug("REST request to get Moderator : {}", id);
        Moderator moderator = moderatorService.findOne(id);
        return Optional.ofNullable(moderator)
            .map(result -> new ResponseEntity<>(
                result,
                HttpStatus.OK))
            .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * DELETE  /moderators/:id : delete the "id" moderator.
     *
     * @param id the id of the moderator to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/moderators/{id}")
    @Timed
    public ResponseEntity<Void> deleteModerator(@PathVariable Long id) {
        log.debug("REST request to delete Moderator : {}", id);
        if(!SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.ADMIN)){
    		return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("moderator", "no Authorities", "you do not have Authorities")).body(null);
    	}
        moderatorService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("moderator", id.toString())).build();
    }

}
